#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd


import base64
import json
import Lib.Logger.log4py as logging
from mj_parser import common_errors
import sys
import traceback
import time

class LandroverWebParser:
    default_result = {
        "vin":               '',
        "model":             '',
        "year":              '',
        "prod_date":         '',
        "air_conditioner":   '',# 空调系统
        "body_style":        '',# 车身款式
        "fabric":            '',# T 内饰面料
        "paint":             '',# P 车身油漆
        "transmission":      '',
        "engine":            '',
        "drive":             '', # DR 驱动器
        "emission":          '',  # EM 排放
        "inner_color":       '',  # 内部环境, 000
        "avs_data":          '',
    }

    def __init__(self, root_dir='.'):
        self.root_dir = root_dir
        self.logger = logging.get_logger("crawler", "FordParserWeb")

    def parse(self, file_name):
        b = common_errors.ERR_SUCCESS
        result_list = self.get_default_result()
        try:
            fobj = open(file_name, encoding='utf_8_sig')
            f_buff = fobj.read()
            catalog = json.loads(f_buff)
            vehicle = catalog['results'][0]

            result_list['vin'] = self.get_value_by_list('vin', vehicle)
            result_list['model'] = self.get_value_by_list('vehicleName', vehicle)
            result_list['year'] = self.get_value_by_list('modelYear', vehicle)
            timestamp = self.get_value_by_list('productionDate', vehicle)
            time_local = time.localtime(int(str(timestamp)[:10]))
            result_list['prod_date'] = dt = time.strftime("%Y%m%d",time_local)
            # 暂时不取air_conditioner,根据primaryFeatureDescriptionList是否有占位
            result_list['air_conditioner'] = '' # self.get_value_by_list('air_conditioner', vehicle)
            result_list['body_style'] = self.get_value_by_list('cabStyle', vehicle)
            result_list['fabric'] = self.get_value_by_list('interiorFabric', vehicle)
            result_list['paint'] = self.get_value_by_list('exteriorPaint', vehicle)
            result_list['transmission'] = self.get_value_by_list('transmission', vehicle)
            result_list['engine'] = self.get_value_by_list('engineType', vehicle)
            result_list['drive'] = self.get_value_by_list('drive', vehicle)
            # 暂时不取emission
            result_list['emission'] = ''# self.get_value_by_list('modelYear', vehicle)
            result_list['inner_color'] = self.get_value_by_list('interiorEnv', vehicle)
            avs_data = ''
            if 'featureIdList' in vehicle:
                feature_id_list = vehicle['featureIdList'] if vehicle['featureIdList'] is not None else ''
                for idx , avs in enumerate(feature_id_list):
                    if idx == 0:
                        avs_data += str(avs)
                    else:
                        avs_data += '|' + str(avs)


            result_list['avs_data'] = avs_data



        except Exception as ex:
            try:
                b = common_errors.ERR_UNKNOWN
                exc_info = sys.exc_info()
                self.logger.error(ex)
            finally:
                traceback.print_exception(*exc_info)
                del exc_info
        # print(result_list)
        return b, result_list

    def get_value_by_list(self, key,list):
        if key in list:
            value = list[key] if list[key] is not None else ''
            return value
        else:
            return ''


    def get_minor_info(self,vehicle_list):
        result_list = []
        #major_list = ['AC', 'BS', 'T', 'P', 'TR', 'EN', 'E', 'W', 'VL', 'VS', 'DR', 'EM', '000']
        for vehicle_item in vehicle_list:
            #if vehicle_item["type"] not in major_list:
            result_list.append(vehicle_item["data"])
        return ' '.join(result_list)

    def get_default_result(self):
        return LandroverWebParser.default_result.copy()


if __name__ == '__main__':
    parser = LandroverWebParser()
    # .\\data\\SALVA2BG2DH800209.json
    code, res = parser.parse('E:\\LandRover\\vin_source_data\\L2CCA2BG9GG336575.json')
    print(code)
    print(res)
